<?php

namespace App\Http\Controllers;

use App\Models\ClusterReport;
use App\Models\ESUnit;
use App\Models\Predict;
use ClickHouseDB\Cluster;
use Illuminate\Http\Request;

use function PHPUnit\Framework\isNull;

class ESUnitController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $data = ESUnit::requestCriteria($request)->paginate($request->query('limit'));
        return $this->respondSuccess($data);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(Request $request, ESUnit $esUnit)
    {
        if($request->limit){
            return $this->respondSuccess($esUnit->esCluster()->paginate($request->query('limit')));
        }
        return $this->respondSuccess($esUnit->load('esCluster'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(ESUnit $esUnit)
    {

    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, ESUnit $eSUnit)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(ESUnit $eSUnit)
    {
        //
    }
    public function report(Request $request, ESUnit $esUnit)
    {
        // $this->validate($request, [
        //     'date_begin' => 'required',
        //     'date_end' => 'required',
        // ]);

        $cluster_ids=$esUnit->esCluster()->pluck('id');
        $begin = $request->input('date_begin'); 
        $end = $request->input('date_end'); 
        if($begin){
            $data = ClusterReport::whereIn('e_s_cluster_id', $cluster_ids)->whereBetween('created_at', [$begin, $end])->get();
        }else{
            $data = ClusterReport::where('e_s_cluster_id', $cluster_ids[0])->limit($request->query('limit', 15))->get();
        }
        return $this->respondSuccess($data);
    }
    public function predict(Request $request, ESUnit $esUnit)
    {
        $cluster_ids=$esUnit->esCluster()->pluck('id');
        $begin = $request->input('date_begin'); 
        $end = $request->input('date_end'); 
        if($begin){
            $data = Predict::where('dev_type', 'App\Models\ESCluster')->whereIn('dev_id', $cluster_ids)->whereBetween('created_at', [$begin, $end])->get();
        }else{
            if(count($cluster_ids)){
                $data = Predict::where('dev_type', 'App\Models\ESCluster')->where('dev_id', $cluster_ids[0])->limit($request->query('limit', 15))->get();
            }else{
                return $this->respondError("此单元未关联簇信息");
            }
        }
        return $this->respondSuccess($data);
    }
}
